require(['./config'],()=>{
    require(['template','header'],(template,header) =>{
        class Shop{
            constructor(){
                this.render()
                this.money()
                this.checksChange()
                this.setALLcheck()
                this.allCheck()
            }
            render(){
                const cart = localStorage.getItem('cart')
                if(cart){
                    this.cart = JSON.parse(cart)
                    $('.cart-table').html(template('cartTemplate',{cart : this.cart}))
                }else{
                    $('.carts').hide()
                    $('.cart-empty').show()
                }
            }
            // 总价计算
            money(){
                    let totalMony = this.cart.reduce((total,shop)=>{
                        if(shop.checked){
                            total += shop.originPrice*shop.count
                            return total
                        }else{
                            return total
                        }
                    },0)
                    $('.price').html(totalMony.toFixed(2))
            }
            checksChange(){
                const _this = this
                $('.checkbox-input').on('change',function(){
                    const id = $(this).parents('tr').data('id')
                    _this.cart = _this.cart.map(shop =>{
                        if (shop.id === id) shop.checked = $(this).prop('checked')
                        return shop
                    })
                    localStorage.setItem('cart', JSON.stringify(_this.cart))
                    _this.money()
                    _this.setALLcheck()
                })
            }
            setALLcheck(){
                 const checks = this.cart.every(shop => shop.checked)
                 $('.checkbox-inputs').prop('checked',checks)
            }
            allCheck(){
                const _this = this
                $('.checkbox-inputs').on('change',function(){
                    _this.cart = _this.cart.map(shop =>{
                        shop.checked = $(this).prop('checked')
                        console.log(shop.checked)
                        return shop
                    })
                    localStorage.setItem('cart', JSON.stringify(_this.cart))
                    _this.money()
                })
            }
        }
        new Shop()
    })
})